package untils

import (
	"bytes"
	"context"
	"dache-server/basic/config"
	__ "dache-server/basic/proto"
	"dache-server/handler/models"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
)

func SyncEsToData() {
	var order models.Order
	orders, _ := order.GetOrderList()
	var wg sync.WaitGroup
	for _, title := range orders {
		wg.Add(1)

		go func(order *models.Order) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(title)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "test",
				DocumentID: strconv.Itoa(int(order.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), config.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(title)
	}
	wg.Wait()

}
func SearchEs(keyword int) (order []*__.OrderList) {
	var buf bytes.Buffer
	var r map[string]interface{}
	var query map[string]interface{}
	if keyword > 0 {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"passager_id": keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := config.Es.Search(
		config.Es.Search.WithContext(context.Background()),
		config.Es.Search.WithIndex("test"),
		config.Es.Search.WithBody(&buf),
		config.Es.Search.WithTrackTotalHits(true),
		config.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	// Print the response status, number of results, and request duration.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})

		id := source["id"].(float64)
		driverId := source["driver_id"].(float64)
		passagerId := source["passager_id"].(float64)
		orderStatus := source["order_status"].(float64)
		payStatus := source["pay_status"].(float64)
		payPrice := source["pay_price"].(float64)

		order = append(order, &__.OrderList{
			Id:          int64(id),
			DriverId:    int64(driverId),
			PassagerId:  int64(passagerId),
			OrderStatus: int64(orderStatus),
			PayStatus:   int64(payStatus),
			PayType:     int64(source["pay_type"].(float64)),
			PayPrice:    float32(payPrice),
		})
	}
	return
}
